import base64
from io import BytesIO

import face_recognition
from flask import Flask, jsonify, request, redirect
from flask_cors import *

app = Flask(__name__)
CORS(app, supports_credentials=True)


# 计算图片数据接口
@app.route('/face_data_get/', methods=['POST'])
def face_data_get():
    try:
        # 读取参数
        image_data = request.json['faceBase64']
        model = request.json['model']

        # 计算代码并响应
        return jsonify(face_data_compute(face_image=image_data, model=model))
    except BaseException:
        # 响应错误信息
        return_data = {
            'code': '-1',
            'msg': '系统发生错误',
            'data': None
        }
        return jsonify(return_data)


# 人脸数据计算函数
def face_data_compute(face_image, pattern='base64', model='hog'):
    # 加载照片
    if 'base64' == pattern:
        image_numpy_array = face_recognition.load_image_file(BytesIO(base64.b64decode(face_image)), mode='RGB')
    elif 'file' == pattern:
        image_numpy_array = face_recognition.load_image_file(face_image, mode='RGB')
    else:
        return {
            'code': '-1',
            'msg': '模式选择错误',
            'data': None
        }

    # 获取人脸位置数据
    if 'hog' != model and 'cnn' != model:
        return {
            'code': '-1',
            'msg': '模型选择错误',
            'data': None
        }
    face_locations = face_recognition.face_locations(image_numpy_array, number_of_times_to_upsample=1, model=model)

    # 判断人脸数量
    if len(face_locations) != 1:
        return {
            'code': '-1',
            'msg': '人脸过多或没有',
            'data': None
        }

    # 计算人脸代码
    face_code = face_recognition.face_encodings(
        image_numpy_array, known_face_locations=face_locations, num_jitters=1, model="small")

    # 编码并返回
    return {
        'code': '0',
        'msg': 'OK',
        'data': face_code[0].tolist()
    }


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=7773, debug=False)
